package adminAuth

import (
	"fmt"
	"net/http"
	"server/dao"
	"server/models"
	"server/utils"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

func Create(c *gin.Context) {
	var doc models.AdminAuth
	c.BindJSON(&doc)
	doc.Status = 1
	doc.CreatedTime = uint64(time.Now().Unix())
	doc.UpdatedTime = uint64(time.Now().Unix())
	err := dao.DB.Create(&doc).Error
	if err != nil {
		c.AbortWithError(500, err)
		return
	}
	c.JSON(
		200,
		utils.DealResponse(utils.Response{
			"data": doc,
		}),
	)
}

func Get(c *gin.Context) {
	page, _ := strconv.ParseInt(c.Query("page"), 10, 32)
	perPage, _ := strconv.ParseInt(c.Query("per_page"), 10, 32)
	name := c.Query("name")

	// 查询条件
	whereStr := []string{"status >= 0"}
	if name != "" {
		whereStr = append(whereStr, " AND name LIKE '%"+name+"%'")
	}
	whereStrLong := strings.Join(whereStr, "")
	// 分页查询
	var list []*models.AdminAuth
	errFind := dao.DB.Model(&models.AdminAuth{}).Select([]string{"id", "name", "type", "pid", "action_key", "created_time", "updated_time"}).Where(whereStrLong).Offset(int(perPage * (page - 1))).Limit(int(perPage)).Find(&list).Error
	if errFind != nil {
		c.AbortWithError(500, errFind)
		return
	}

	var count int64
	errCount := dao.DB.Model(&models.AdminAuth{}).Where(whereStrLong).Count(&count).Error
	if errCount != nil {
		c.AbortWithError(500, errCount)
		return
	}
	// 正常返回数据
	c.JSON(
		200,
		utils.DealResponse(utils.Response{
			"data": gin.H{
				"list": list,
				"page": gin.H{
					"page":     page,
					"per_page": perPage,
					"total":    count,
				},
			},
		}),
	)
}

func Update(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok {
		c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
		return
	}
	var doc models.AdminAuth
	c.BindJSON(&doc)
	fmt.Printf("%#v\n", doc)
	var updateDoc = map[string]interface{}{
		"Name":        doc.Name,
		"Type":        doc.Type,
		"Pid":         doc.Pid,
		"ActionKey":   doc.ActionKey,
		"UpdatedTime": uint64(time.Now().Unix()),
	}
	err := dao.DB.Model(&doc).Where("id=?", id).Updates(updateDoc).Error
	if err != nil {
		c.AbortWithError(500, err)
		return
	}
	c.JSON(
		200,
		utils.DealResponse(utils.Response{
			"data": updateDoc,
		}),
	)
}

func Delete(c *gin.Context) {
	id, ok := c.Params.Get("id")
	if !ok {
		c.JSON(http.StatusOK, gin.H{"error": "无效的id"})
		return
	}
	err := dao.DB.Model(&models.AdminAuth{}).Where("id=?", id).Updates(map[string]interface{}{
		"Status": -1,
	}).Error
	if err != nil {
		c.AbortWithError(500, err)
		return
	}
	c.JSON(
		200,
		utils.DealResponse(utils.Response{
			"data": "ok",
		}),
	)
}
